/*
 * @Author: gk 
 *  文件资源
 * @Date: 2018-03-15 14:44:57 
 * @Last Modified by: gk
 * @Last Modified time: 2018-05-09 14:31:14
 */
layui.config({}).use(['element', 'zlConfig', 'zlContext', 'zltreemenu', 'zlExcel', 'table', 'layer', 'form', 'zlPinYin', 'upload'], function (exports) {
	var $ = layui.$,
		zlContext = layui.zlContext,
		zltreemenu = layui.zltreemenu,
		layer = layui.layer,
		table = layui.table,
		form = layui.form,
		upload = layui.upload,
		zlPinYin = layui.zlPinYin,
		zlConfig = layui.zlConfig,
		statusName = zlConfig.global.result.statusName,
		msgName = zlConfig.global.result.msgName,
		dataName = zlConfig.global.result.dataName,
		OK = zlConfig.global.result.okState,
		zlExcel = layui.zlExcel,
		// fullheight = zlContext.setMaxHeihgt(0),
		fullheight = 'full-30',
		customCurr = 1;

	var treeObj,
		fromlayerIndex,
		isloadsearch = false,
		treeAction = {
			loadTree: function () {
				//创建zTree组件
				treeObj = zltreemenu.render('fileTree', {
					dataurl: $('#fileTree').attr('url'),
					type: 'get',
					name: 'ZDZ_MINGC',
					isMove: false,
					search: false
				}, {
					onClick: function (event, treeId, treeNode) {
						//触发注册刷新的事件
						customCurr = 1;
						treeAction.raiseResDataEvent(treeNode);
					},
					onAsyncSuccess: function (event, treeId, treeNode, msg) {
						treeObj.expandAll(true);
						treeObj.selectNode(treeObj.getNodes()[0]);
						treeAction.raiseResDataEvent(treeObj.getNodes()[0]);
					}
				})
			},
			/**发起刷新明细资料的事件 */
			raiseResDataEvent: function (node) {
				gridAction.refresh(node);
			},
		}
	//加载树
	treeAction.loadTree();
	//渲染文件资源列表
	var fileresTb = table.render({
		elem: '#tbFileres',
		sortload: true,
		height: fullheight,
		response: zlConfig.global.gridResponse,
		limit: 20,
		limits: [20, 50, 100, 200, 500, 1000],
		page: true,
		updId: "DCE3B899AD564BD28026AFCF1FC2CD3B",
		toolbar: "#toolbarFileres",
		defaultToolbar: ['filter'],
		sortload: true,
		cols: [
			[ //表头
				{
					type: 'numbers',
					fixed: 'left',
					title: '#'
				}, {
					type: 'checkbox',
					fixed: 'left'
				}, {
					field: 'WJZY_MINGC',
					title: '名称',
					sort: true,
					sortload: false,
					width: 300
				}, {
					field: 'WJZY_BIANH',
					title: '编号',
					sort: true,
					width: 150
				}, {
					field: 'WJZY_ZIYLJ',
					title: '资源',
					sort: true,
					width: 150,
					templet: '#fileresTbLj'
				}, {
					fixed: 'right',
					width: 150,
					title: '操作',
					align: 'center',
					toolbar: '#barFileres'
				}
			]
		],
		event: {
			onRowdbClick: function (field, row) {
				gridAction.viewRow(row);
			}
		}
	});
	zlContext.noData($('#tbFileres').siblings('div').find('div.layui-table-main'))

	var gridAction = {
		currentEditObj: undefined,
		gridEdit: function (catlog, row, type, readonly) {
			var nodes = treeObj.getSelectedNodes(),
				btnText = '资源',
				accept = 'file',
				acceptMime = '',
				exts = '';
			var curFileType = nodes[0]['ZDZ_ZIDZ'];
			switch (nodes[0]['ZDZ_ZIDZ']) {
				case '0': // 图标||图片
					btnText = '图标';
					accept = 'images';
					acceptMime = 'image/*';
					exts = 'jpg|png|gif|bmp|jpeg';
					break;
				case '1': // 图标||图片
					btnText = '图片';
					accept = 'images';
					acceptMime = 'image/*';
					exts = 'jpg|png|gif|bmp|jpeg';
					break;
				case '2': // 文本
					btnText = '文本';
					acceptMime = 'file/txt';
					exts = 'txt';
					break;
				case '3': // pdf
					btnText = 'pdf';
					acceptMime = 'file/pdf';
					exts = 'pdf';
					break;
				case '4': // word
					btnText = 'word';
					acceptMime = 'file/doc,file/docx,file/docm,file/dotx,file/dotm';
					exts = 'doc|docx|docm|dotx|dotm';
					break;
				case '5': // excel
					btnText = 'excel';
					acceptMime = 'file/xls,file/xlsx,file/xlsm,file/xltx,file/xltm,file/xlsb,file/xlam';
					exts = 'xls|xlsx|xlsm|xltx|xltm|xlsb|xlam';
					break;
			}
			var readonly = readonly && readonly != 0 ? 'disabled' : '';
			var frm = [
				'<div class="site-block" lay-filter="divgridField"> <form id ="frmGridField" class="layui-form"  action="">', '	<div class="layui-form-item layui-hide">', '		<div class="layui-input-block">', '			<input type="text" name="EDITTYPE" class="layui-input">', '			<input type="text" name="RWID" class="layui-input">', '			<input type="text" name="WJZY_LEIX" class="layui-input">', '		</div>', '	</div>', '	<div class="layui-form-item">', '		<label class="layui-form-label">名称</label>', '		<div class="layui-input-block">', '			<input type="text" name="WJZY_MINGC" ' + readonly + ' lay-verify="required" placeholder="请输入名称" class="layui-input" maxlength="50">', '		</div>', '	</div>', '	<div class="layui-form-item">', '		<label class="layui-form-label">编号</label>', '		<div class="layui-input-block">', '			<input type="text" name="WJZY_BIANH" ' + readonly + ' lay-verify="required" placeholder="请输入编号" class="layui-input" maxlength="50">', '		</div>', '	</div>', '	<div class="layui-form-item">', '		<label class="layui-form-label">路径</label>', '		<div class="layui-input-block">', '			<input type="text" name="WJZY_ZIYLJ" disabled lay-verify="required" placeholder="请上传文件" class="layui-input"> ', '		</div>', '	</div>', '	<div class="layui-form-item">', '		<div class="layui-input-block">', '			<div class="layui-upload">', '	  			<button type="button" class="layui-btn' + (readonly == 'disabled' ? ' layui-hide"' : '"') + ' id="btnUploadfile">上传' + btnText + '文件</button>', '				<blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">', '					<div class="layui-upload-list" id="imgPrieviewPic"></div>', '				</blockquote>', '			</div>', '		</div>', '	</div>', '	<div class="layui-form-item' + (readonly == 'disabled' ? ' layui-hide"' : '"') + '>', '		<div class="layui-input-block">', '		  <button class="layui-btn" lay-submit lay-filter="frmGridField">保存</button>', '		</div>', '	</div>', '</form></div>'
			];
			layer.open({
				type: 1,
				title: readonly == 'disabled' ? '查看' : (type == 'edit' ? '编辑' : '新增'),
				id: 'corefileresLayer',
				area: ['100%', '100%'],
				content: frm.join(''),
				success: function (layero, index) {
					// var nodes = treeObj.getSelectedNodes();
					var extsStr = exts.split('|').join(',');
					$('#btnUploadfile').hover(
						function () {
							layer.tips('注意：只允许上传后缀名为 ' + extsStr + ' 的文件', '#btnUploadfile', {
								tips: [2, '#277FD0'],
								time: 0
							});
						},
						function () {
							layer.closeAll('tips');
						}
					);

					upload.render({
						elem: '#btnUploadfile',
						accept: accept, //所有的文件
						acceptMime: acceptMime,
						exts: exts,
						url: layui.cache['contentPath'] + '/manager/corefilesres/upload/',
						data: {
							catlog: gridAction.getCurrentCalog()
						},
						// before: function (obj) {},
						done: function (res) {
							if (res[statusName] != OK) {
								$('#imgPrieviewPic').empty();
								return layer.msg('上传失败' + res[msgName]);
							} else {
								$('#imgPrieviewPic').empty();
								$(res[dataName]).each(function (index, obj) {
									if ('0' == curFileType || '1' == curFileType) {
										$('#imgPrieviewPic').append('<img src="' + layui.cache['contentPath'] + obj["newFileName"] + '" alt="' + obj["oldFileName"] + '" class="layui-upload-img">')
									} else {
										$('#imgPrieviewPic').append('<img src="' + layui.cache['contentPath'] + '/static/appdata/filesres/res-type/' + curFileType + '_type.png" class="layui-upload-img">')
									}
									$('#frmGridField input[name=WJZY_ZIYLJ]').val(obj["newFileName"]);
								});
							}
						},
						error: function () {
							layer.msg('上传失败');
						}
					});
					if (type == 'edit') {
						zlContext.autoFill($('#frmGridField'), row);
						$('#frmGridField input[name=EDITTYPE]').val('edit');
						$('#frmGridField input[name=WJZY_LEIX]').val(nodes[0]['ZDZ_ZIDZ']);
						$('#imgPrieviewPic').empty();
						if ('0' == curFileType || '1' == curFileType) {
							$('#imgPrieviewPic').append('<img src="' + layui.cache['contentPath'] + row['WJZY_ZIYLJ'] + '" class="layui-upload-img">')
						} else {
							$('#imgPrieviewPic').append('<img src="' + layui.cache['contentPath'] + '/static/appdata/filesres/res-type/' + curFileType + '_type.png" class="layui-upload-img">')
						}
						form.render();
					} else {
						/**设置隐藏属性*/
						$('#frmGridField input[name=EDITTYPE]').val('new');
						$('#frmGridField input[name=WJZY_LEIX]').val(nodes[0]['ZDZ_ZIDZ']);
						//由于layui是主动刷新需要重新刷新才能显示出状态
						form.render();
						$('#frmGridField input[name=WJZY_MINGC]').change(function () {
							var v = $('#frmGridField input[name=WJZY_MINGC]').val();
							/**设置文件资源名 */
							var v1 = zlPinYin.C(v);
							$('#frmGridField input[name=WJZY_BIANH]').val(v1.substring(0, 50));
							form.render();
						});
					}
					fromlayerIndex = index;
				},
				cancel: function (index, layero) {
					if (type == 'edit' && readonly != 'disabled') {
						zlContext.isFormDataChange('frmGridField', gridAction.currentEditObj.data, gridAction, index);
						return false;
					}
				}
			});
		},
		getCurrentCalog: function () {
			var nodes = treeObj.getSelectedNodes();
			return nodes[0]['ZDZ_BIANH'];
		},
		viewRow: function (row) {
			gridAction.gridEdit(null, row, 'edit', true);
		},
		newRow: function () {
			var nodes = treeObj.getSelectedNodes();
			if (nodes.length == 0) {
				zlContext.warnMsg('请选择节点');
				return;
			}
			if (nodes[0]['WJZY_LEIX'] == 2) {
				zlContext.warnMsg('模型类型是目录无法新增文件资源');
				return;
			}
			gridAction.gridEdit(null, null, 'new');
		},
		editRow: function (row) {
			gridAction.gridEdit(null, row, 'edit');
		},
		deleteRows: function (rows, type) {
			if (rows.length == 0) {
				zlContext.warnMsg('请选择需要删除的文件资源');
				return;
			}
			zlContext.confirm('询问', '是否要删除选择的文件资源?', function (index) {
				// var param = { id: rows[0]['RWID'] };
				var ids = [];
				for (var i = 0; i < rows.length; i++) {
					ids.push(rows[i]['RWID']);
				}
				//提交删除
				zlContext.deletePost(layui.cache['contentPath'] + '/manager/corefilesres/remove', {
					"ids": ids.join(',')
				}, function (result) {
					if (result[statusName] == OK) {
						if (gridAction.currentEditObj && type == 'single') {
							gridAction.currentEditObj.del();
							gridAction.currentEditObj = undefined;
							var $pageBox = $('#tbFileres').siblings('div.layui-table-view').find('span.layui-laypage-count'),
								currCount = $pageBox.html().replace(/[^0-9]/ig, "");
							$pageBox.html('共 ' + --currCount + ' 条')
						} else {
							gridAction.refreshGrid('new', null);
						}
						zlContext.successMsg('删除成功');
					} else {
						zlContext.errorMsg(result[msgName]);
					}
				});
				layer.close(index);
			});
		},
		sumbit: function (fields) {
			if (!fields.WJZY_ZIYLJ) {
				zlContext.warnMsg('请上传文件资源');
				return false;
			}
			var editType = $('#frmGridField input[name=EDITTYPE]').val();
			if (editType == 'new') {
				zlContext.put(layui.cache['contentPath'] + '/manager/corefilesres/add', fields, function (result) {
					if (result[statusName] == OK) {
						gridAction.refreshGrid(editType, result[dataName]);
						layer.close(fromlayerIndex);
						zlContext.successMsg('保存成功');
						return true;
					} else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			}
			if (editType == 'edit') {
				zlContext.post(layui.cache['contentPath'] + '/manager/corefilesres/modify', fields, function (result) {
					if (result[statusName] == OK) {
						gridAction.refreshGrid(editType, fields);
						layer.close(fromlayerIndex);
						zlContext.successMsg('保存成功');
						return true;
					} else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			}
			return false;
		},
		search: function () {
			var nodes = treeObj.getSelectedNodes(),
				param = {}
			if (nodes.length > 0 && nodes[0]['ZDZ_ZIDZ']) {
				param['WJZY_LEIX'] = nodes[0]['ZDZ_ZIDZ'];
			}
			if ($('#edtSeacherValue').val().length > 0) {
				param['SEARCHVALUE'] = $('#edtSeacherValue').val();
				isloadsearch = true;
			}
			layui.event('WM_USERDEF',
				zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, param);
		},
		refresh: function (node) {
			var currNode = node;
			if (!node) {
				var nodes = treeObj.getSelectedNodes();
				if (nodes.length > 0)
					currNode = nodes[0];
			}
			$('#edtSeacherValue').val("")
			var param = {}
			if (currNode['ZDZ_ZIDZ']) {
				param['WJZY_LEIX'] = currNode['ZDZ_ZIDZ'];
			}
			param['SEARCHVALUE'] = $('#edtSeacherValue').val();
			layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, param);
		},
		refreshGrid: function (type, row) {
			/**刷新行 */
			if (type == 'edit' && gridAction.currentEditObj) {
				gridAction.currentEditObj.update(row);
			} else {
				var nodes = treeObj.getSelectedNodes(),
					addLoading = layer.load();
				
				fileresTb.reload({
					where: {
						'WJZY_LEIX': nodes[0]['ZDZ_ZIDZ'],
						'SEARCHVALUE': ''
					},
					page: {
						curr: customCurr
					},
					done: function (res, curr, count) {
						layer.close(addLoading);
						customCurr = curr;
					}
				});
			}
		}
	}
	$('#btndc').on('click', function () {
		var excelmodei = {};
		excelmodei.tableid = 'tbFileres';
		zlExcel.excelpopform(excelmodei);
	});
	// $('#btnSeacher').on('click', function () {
	// 	customCurr = 1;
	// 	gridAction.search();
	// });
	$('.zl-container').on('keyup', '#edtSeacherValue', function (event) {
		var keyCode = event.keyCode;
		customCurr = 1;
		$('.zl-container').attr('data-search', $(this).val())
		if (keyCode == 13) {
			gridAction.search();
		}
		if ((keyCode == '46' || keyCode == '8' || (event.ctrlKey && keyCode == '86')) && $(this).val() == '' && isloadsearch) {
			$('#btnSeacher').trigger('click');
			isloadsearch = false;
		}
	});

	//头工具栏事件
	table.on('toolbar(tbFileres)', function (obj) {
		var checkStatus = table.checkStatus(obj.config.id);
		switch (obj.event) {
			case 'btnSeacher':
				customCurr = 1;
				gridAction.search();
				break;
			case 'addFileres':
				gridAction.newRow();
				break;
			case 'deleteFileres':
				var rows = checkStatus.data;
				gridAction.deleteRows(rows, 'multi');
				break;
			case 'refreshFileres':
				gridAction.refresh(null);
                break;            
		}
	});
	//监听行工具事件
	table.on('tool(tbFileres)', function (obj) {
		var row = obj.data, //获得当前行数据
			layEvent = obj.event; //获得当前行 tr 的DOM对象
		if (layEvent === 'detail') { //查看
			gridAction.viewRow(row)
		} else if (layEvent === 'del') { //删除
			gridAction.currentEditObj = obj;
			gridAction.deleteRows([row], 'single');
		} else if (layEvent === 'edit') { //编辑
			gridAction.currentEditObj = obj;
			gridAction.editRow(row);
		}
	});
	//提交
	form.on('submit(frmGridField)', function (frm) {
		if ($(frm.elem).hasClass('getField')) {
			gridAction.newFields = frm.field;
			return false;
		}
		return gridAction.sumbit(frm.field);
	});
	//监听刷新的事件
	layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (param) {
		var index = layer.msg('数据查询中，请稍候...', {
			icon: 16,
			time: false,
			shade: 0.1
		});
		var loadGridData = function (tableId, url, param) {
			fileresTb.reload({
				url: url,
				height: fullheight,
				method: 'post',
				where: param,
				page: {
					curr: customCurr
				},
				done: function (res, curr, count) {
					$('#edtSeacherValue').val($('.zl-container').attr('data-search'))
					layer.close(index);
					customCurr = curr;
				}
			});
		}
		//刷新
		loadGridData('tbFileres', layui.cache['contentPath'] + '/manager/corefilesres/query', param);
	});

	$(window).on('resize', function () {
		zlContext.setMaxHeihgt(0);
	}).resize();
});